package cn.edu.jxau.test;

import java.util.Arrays;

public class BitMap {

	public static void main(String[] args) {

		BitMap bitMap = new BitMap(64 + 64);
		System.out.println(bitMap.capacity);
	}

	private int capacity;
	private int length;
	private int[] bit;
	private static final int SHIFT = Integer.BYTES + 1;
	private static final int MASK;

	static {

		int mask = 0;
		for (int i = 0; i < SHIFT; i++) {
			mask = mask | 1 << i;
		}
		MASK = mask;
	}

	public BitMap(int capacity) {

		bit = new int[(capacity - 1) / Integer.SIZE + 1];
		this.capacity = bit.length * Integer.SIZE;
	}

	public void clear(int i) {

		int index = i >> SHIFT;
		int mod = i & MASK;
		bit[index] = bit[index] & (~(1 << mod));
	}

	public void set(int i) {

		int index = i >> SHIFT;
		int mod = i & MASK;
		bit[index] = bit[index] | (1 << mod);
	}

	/**
	 * 返回当前bitMap能够存储的位数
	 * 
	 * @return
	 */
	public int capacity() {
		return capacity;
	}

	/**
	 * 返回当前bitMap的逻辑位数，即最后一个被置为1的位的索引
	 * 
	 * @return
	 */
	public int length() {

		System.out.println(Arrays.toString(bit));
		int i = 0;
		for (; i < bit.length; i++) {
			if (bit[i] == 0) {
				if (i == 0) {
					return 0;
				} else {
					i--;
				}
				break;
			}
		}
		int length = i >> SHIFT;
		int last = 0;
		for (int j = 0; j < Integer.SIZE - 1; j++) {
			if (((bit[i] >> j) & 1) == 1) {
				last = j;
			}
		}
		return length + last;
	}

	public boolean get(int i) {
		return false;
	}

	@Override
	public String toString() {

		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < bit.length; i++) {
			builder.append(bit[i]).append("\n");
		}
		builder.deleteCharAt(builder.length() - 1);
		return builder.toString();
	}
}
